package com.cjy.expenses.service.impl;

import com.base.common.ConfigConstants;
import com.base.common.enums.*;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.*;
import com.base.common.persistent.model.*;
import com.base.common.utils.StringUtils;
import com.base.common.webservice.entity.HZService.UserRevGetFeeListbyLocklogoBean;
import com.base.common.webservice.entity.SYS86Service.UserRevGetFeeListByResBean;
import com.base.common.webservice.util.HZServiceUtil;
import com.base.common.webservice.util.SYS86ServiceUtil;
import com.cjy.expenses.service.ExpensesService;
import com.cjy.payment.alipay.config.AlipayConfig;
import com.cjy.payment.unionpay.acp.demo.Form05_6_2_AppConsume;
import com.cjy.payment.unionpay.acp.demo.Form05_6_3_Query;
import com.cjy.payment.unionpay.acp.demo.VerifyAppData;
import com.cjy.payment.weixin.config.WeixinConfig;
import com.cjy.payment.weixin.util.EasyUtil;
import com.cjy.payment.weixin.util.QueryOrder;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 缴费service的实现类
 * 
 * @author kat.luhongkai
 *
 */

@Service("expensesService")
public class ExpensesServiceImpl implements ExpensesService {

	@Resource
	private ExpensesMapper expensesMapper;

	@Resource
	private TerminalMapper terminalMapper;

    @Resource
    private UserMapper userMapper;

	@Resource
	private CompoundsMapper compoundsMapper;

	@Resource
	private TransactionDetailMapper transactionDetailMapper;

	@Resource
	private TransactionMapper transactionMapper;

	@Resource
	private VillageConfigMapper villageConfigMapper;

	@Resource
	private ShopOrderMapper shopOrderMapper;

	@Resource
	private ShopOrderItemMapper shopOrderItemMapper;
	
	@Resource
	private ShopUserMapper shopUserMapper;

	@Resource
	private TNewsMapper tNewsMapper;

	@Resource
	private TShopsMapper tShopsMapper;
	
	@Resource
	private ShopUserReceivingInfoMapper shopUserReceivingInfoMapper;

	/*
	 * @Override public PaymentList getExpensesInfo(int userId) { PaymentList
	 * paymentList = new PaymentList(); List<Expenses> expensesList = new
	 * ArrayList<Expenses>(); List<Paied> paiedList = new ArrayList<Paied>();
	 * 
	 * // 查询当前欠费款项 expensesList =
	 * expensesMapper.queryExpensesByUserIdAndArrearage(userId); // 获取已预交金额
	 * paiedList = expensesMapper.queryPaiedByUserIdAndNoCharge(userId);
	 * 
	 * double sum = 0.00; double paying = 0.00;
	 * 
	 * // 匹配欠费类型 for(Expenses expenses : expensesList){ sum +=
	 * expenses.getMoney(); double a = -1; for(Paied paied : paiedList){ if
	 * (expenses.getCategories() == paied.getCategories()) { a = a +
	 * (expenses.getMoney() - paied.getMoney()); } } if(a >= 0){ paying += a +
	 * 1; } else { paying += expenses.getMoney(); }
	 * 
	 * }
	 * 
	 * double paieds = 0.00;
	 * 
	 * for(Paied paied : paiedList){ paieds += paied.getMoney();
	 * if(paied.getCategories() == 0) { paying -= paied.getMoney(); } }
	 * 
	 * paymentList.setExpenses(expensesList);
	 * paymentList.setTotal(formatDouble(sum));
	 * paymentList.setPaied(formatDouble(paieds));
	 * paymentList.setPaying(formatDouble(paying)); return paymentList; }
	 */

	public double formatDouble(double num) {
		return Double.valueOf(new java.text.DecimalFormat("#.00").format(num));
	}

	@Transactional
	@Override
	public Map<String, Object> getAlipayInfo(int fee, String revFeeIdsArr,
			String terminalCode, int userId, int bid) throws Exception {
		/*System.out.println("getAlipayInfo*********************");*/
		String out_trade_no = EasyUtil.genOutTradNo();
		Map<String, Object> map = new HashMap<String, Object>();

		List<Terminal> terminals = getTerminals(terminalCode, bid);
		if (terminals.size() == 0) {
			throw new RuntimeException();
		}
		
		Transaction transaction = new Transaction();
		transaction.setOut_trade_no(out_trade_no);
		transaction.setFee(fee);
		transaction.setTerminal(new Terminal().setId(terminals.get(0).getId()));
		transaction.setUser(new User().setId(userId));
		transactionMapper.addTransaction(transaction);

		Transaction tra = transactionMapper.queryByOut_trade_no(out_trade_no);
		Transaction tran = new Transaction();
		tran.setId(tra.getId());
		List<String> revFeeIds = JsonUtil.string2Obejct(revFeeIdsArr,
				List.class);
		for (String revFees : revFeeIds) {
			Map<String, String> revFee = JsonUtil.string2Obejct(revFees,
					Map.class);
			TransactionDetail transactionDetail = new TransactionDetail();
			transactionDetail
					.setRevFeeId(String.valueOf(revFee.get("revFeeId")));
			transactionDetail.setFee(Integer.valueOf(revFee.get("revFee")
					.toString()));
            if(StringUtils.isNotEmptyByTrim(revFee.get("CusID"))) {
                transactionDetail.setCusID(String.valueOf(revFee.get("CusID")).trim());
            } else {
                throw new Exception();
            }
			transactionDetail.setIpItemName(String.valueOf(revFee.get("IpItemName")));
			transactionDetail.setTransaction(tran);
			transactionDetailMapper.addTransactionDetail(transactionDetail);
		}
		map.put("out_trade_no", out_trade_no);
		System.out.println(AlipayConfig.alipay_notify_url);
		map.put("notifyUrl", AlipayConfig.alipay_notify_url);
		return map;
	}

    @Transactional
	@Override
	public Map<String, Object> getShopAlipayInfo(int fee, String username, String phone, String address, String terminalCode, int userType, String revFeeIdsArr, String cUname) {
		String out_trade_no = EasyUtil.genOutTradNo();
		Map<String, Object> map = new HashMap<String, Object>();
		addShopOrder(fee, username, phone, address, terminalCode, userType, revFeeIdsArr, out_trade_no, PayWays.ALIPAY.getValue(), cUname);



		/*Transaction tra = transactionMapper.queryByOut_trade_no(out_trade_no);
		Transaction tran = new Transaction();
		tran.setId(tra.getId());
		List<String> revFeeIds = JsonUtil.string2Obejct(revFeeIdsArr,
				List.class);
		for (String revFees : revFeeIds) {
			Map<String, String> revFee = JsonUtil.string2Obejct(revFees,
					Map.class);
			TransactionDetail transactionDetail = new TransactionDetail();
			transactionDetail
					.setRevFeeId(String.valueOf(revFee.get("revFeeId")));
			transactionDetail.setFee(Integer.valueOf(revFee.get("revFee")
					.toString()));
			transactionDetail.setCusID(String.valueOf(revFee.get("CusID")));
			transactionDetail.setIpItemName(String.valueOf(revFee.get("IpItemName")));
			transactionDetail.setTransaction(tran);
			transactionDetailMapper.addTransactionDetail(transactionDetail);
		}*/
		map.put("out_trade_no", out_trade_no);
		System.out.println(AlipayConfig.alipay_notify_url);
		map.put("notifyUrl", AlipayConfig.alipay_notify_url);
		return map;
	}

	private void addShopOrder(int fee, String username, String phone, String address, String terminalCode, int userType, String revFeeIdsArr, String out_trade_no, int payWay, String cUname) {
		// 订单主表插入
		ShopOrder shopOrder = new ShopOrder();
		shopOrder.setAddress(address);
		shopOrder.setFee(fee);
		shopOrder.setOutTradeNo(out_trade_no);
		shopOrder.setPaymentMethod(payWay);
		shopOrder.setUsername(username);
		shopOrder.setPhone(phone);
		shopOrder.setUserType(userType);
		shopOrder.setTerminalCode(terminalCode);
		shopOrderMapper.insertSelective(shopOrder);

		// 订单详情插入
		ShopOrder shopOrder1 = new ShopOrder();
		shopOrder1.setOutTradeNo(out_trade_no);
		ShopOrder order = shopOrderMapper.selectByCondition(shopOrder1).get(0);
		List<String> shopOrderItems = new ArrayList<>();
		shopOrderItems = JsonUtil.string2Obejct(revFeeIdsArr, shopOrderItems.getClass());
		shopOrderItems.stream().forEach((item) -> {
			ShopOrderItem shopOrderItem = JsonUtil.string2Obejct(item, ShopOrderItem.class);
			shopOrderItem.setOrderId(order.getId());
            shopOrderItem.setcUname(cUname);
			/*MultipleDataSource.setDataSourceKey("shopDataSource");
			shopOrderItem.setcUname(tShopsMapper.selectByPrimaryKey((long) tNewsMapper.selectByPrimaryKey(shopOrderItem.getRid()).getCtypeB()).getcUname());
			MultipleDataSource.setDataSourceKey("sqlserverDataSource");*/
			shopOrderItemMapper.insertSelective(shopOrderItem);
		});
	}

	@Override
	public List<Map<String, Object>> getExpensesInfo(String ResID,
			String startTime, String endTime, int compoundsId, String categories) {
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        String c = villageConfigMapper.getProjectID(compoundsId);
        List<Compounds> compoundses = compoundsMapper.queryCompoundsById(compoundsId);

        if(compoundses.get(0).getCompany().getId() == 5) {
            List<UserRevGetFeeListbyLocklogoBean> userRevGetFeeListbyLocklogoBeans = HZServiceUtil.getUserRevGetFeeListbyLocklogoBean(userMapper.queryUserByResID(ResID).get(0).getCode(), c, "0");
            userRevGetFeeListbyLocklogoBeans.stream().forEach((item) -> {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("ID", item.getID());
                map.put("RepYears", item.getRepYears());
                map.put("PriRev", item.getPriRev());
                map.put("PriPaid", item.getPriPaid());
                map.put("PriFailures", item.getPriFailures());
                map.put("LFRev", item.getLFRev());
                map.put("LFPaid", item.getLFPaid());
                map.put("LFFailures", item.getLFFailures());
                map.put("RevAbstract", item.getRevAbstract());
                map.put("IpItemName", item.getIpItemName());
                map.put("LockLogo", item.getLockLogo());
                maps.add(map);
            });
        } else {


            List<UserRevGetFeeListByResBean> userRevGetFeeListByResBeans = SYS86ServiceUtil
                    .getUserRev_GetFeeListByRes(ResID, startTime, endTime, c,
                            categories);

            for (UserRevGetFeeListByResBean userRevGetFeeListByResBean : userRevGetFeeListByResBeans) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("ID", userRevGetFeeListByResBean.getID());
                map.put("RepYears", userRevGetFeeListByResBean.getRepYears());
                map.put("PriRev", userRevGetFeeListByResBean.getPriRev());
                map.put("PriPaid", userRevGetFeeListByResBean.getPriPaid());
                map.put("PriFailures", userRevGetFeeListByResBean.getPriFailures());
                map.put("LFRev", userRevGetFeeListByResBean.getLFRev());
                map.put("LFPaid", userRevGetFeeListByResBean.getLFPaid());
                map.put("LFFailures", userRevGetFeeListByResBean.getLFFailures());
                map.put("RevAbstract", userRevGetFeeListByResBean.getRevAbstract());
                map.put("IpItemName", userRevGetFeeListByResBean.getIpItemName());
                map.put("CusName", userRevGetFeeListByResBean.getCusName());
                map.put("CusID", userRevGetFeeListByResBean.getCusID());
                map.put("LockLogo", userRevGetFeeListByResBean.getLockLogo());
                maps.add(map);
            }
        }

		return maps;
	}



	private List<Terminal> getTerminals(String terminalCode, int bid) {
		List<Terminal> terminals = new ArrayList<Terminal>();
		switch (bid) {
		case 0:
			terminals = terminalMapper.queryTerminalByCodesRegisted(null, null,
					terminalCode, AppType.CJY.getValue());
			break;
		case 1:
			terminals = terminalMapper.queryTerminalByCodesRegisted(null, null,
					terminalCode, AppType.YGJ.getValue());
			break;
		case 3:
			terminals = terminalMapper.queryTerminalByCodesRegisted(null,
					terminalCode.trim(), null, AppType.CJY.getValue());
			break;
		case 4:
			terminals = terminalMapper.queryTerminalByCodesRegisted(null,
					terminalCode, null, AppType.YGJ.getValue());
			break;
		default:
			throw new RuntimeException();
		}
		return terminals;
	}

	@Transactional
	@Override
	public Map<String, Object>  getWeixinPayInfo(int fee, String revFeeIdsArr,
			String terminalCode, int userId, int bid, String body) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		String out_trade_no = RandomUtils.nextInt(new Random(), 10000) + "" + System.currentTimeMillis();
		List<Terminal> terminals = getTerminals(terminalCode, bid);
		Transaction transaction = new Transaction();
		transaction.setOut_trade_no(out_trade_no);
		transaction.setFee(fee);
		transaction.setTerminal(new Terminal().setId(terminals.get(0).getId()));
		transaction.setUser(new User().setId(userId));
		transactionMapper.addTransaction(transaction);
		
		Transaction tra = transactionMapper.queryByOut_trade_no(out_trade_no);
		List<String> revFeeIds = JsonUtil.string2Obejct(revFeeIdsArr,
				List.class);
		for (String revFees : revFeeIds) {
			Map<String, String> revFee = JsonUtil.string2Obejct(revFees,
					Map.class);
			TransactionDetail transactionDetail = new TransactionDetail();
			transactionDetail
					.setRevFeeId(String.valueOf(revFee.get("revFeeId")));
			transactionDetail.setFee(Integer.valueOf(revFee.get("revFee")
					.toString()));
			if(StringUtils.isNotEmptyByTrim(revFee.get("CusID"))) {
                transactionDetail.setCusID(String.valueOf(revFee.get("CusID")).trim());
            } else {
                throw new Exception();
            }
			transactionDetail.setIpItemName(String.valueOf(revFee.get("IpItemName")));
			transactionDetail.setTransaction(tra);
			transactionDetailMapper.addTransactionDetail(transactionDetail);
		}
		
		/*UnifiedOrderParam unifiedOrderParam = new UnifiedOrderParam();
		unifiedOrderParam.setBody(body);
//		System.out.println(body);
		unifiedOrderParam.setAttach(out_trade_no);
		unifiedOrderParam.setOut_trade_no(out_trade_no);
		unifiedOrderParam.setNonce_str(com.cjy.payment.weixin.util.EasyUtil.genNonceStr());
		unifiedOrderParam.setTotal_fee(fee + "");
		unifiedOrderParam.setSpbill_create_ip(ConfigConstants.SERVERIP);
		unifiedOrderParam.setTrade_type("APP");
		unifiedOrderParam.setNotify_url(WeixinConfig.weixin_notify_url);
		
		HttpURLConnection connection = HttpClientUtil.getHttpURLConnection("http://localhost:8080/Payment/servlet/PaymentServlet");
		connection.setDoOutput(true);   
		connection.setDoInput(true);   
		connection.setUseCaches(false);   
		connection.setRequestProperty("Content-type", "application/x-java-serialized-object");   
		connection.setRequestMethod("POST");
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(connection.getOutputStream());
		objectOutputStream.writeObject(unifiedOrderParam);
		objectOutputStream.flush();
		objectOutputStream.close();
		
		ObjectInputStream inputStream = new ObjectInputStream(connection.getInputStream());
		UnifiedOrderResult unifiedOrderResult = (UnifiedOrderResult) inputStream.readObject();
		
		result.put("payReq", GeneratePaymentOrder.genPayReq(unifiedOrderResult.getPrepay_id()));
		result.put("out_trade_no", out_trade_no);*/
		
		result.put("out_trade_no", out_trade_no);
		result.put("notifyUrl", WeixinConfig.weixin_notify_url);
		return result;
	}

	@Override
	public Map<String, Object> getShopWeixinPayInfo(int fee, String username, String phone, String address, int userType, String revFeeIdsArr, String terminalCode, String body, String cUname) throws InstantiationException, IllegalAccessException, IOException, ClassNotFoundException {
		Map<String, Object> result = new HashMap<String, Object>();
		String out_trade_no = RandomUtils.nextInt(new Random(), 10000) + "" + System.currentTimeMillis();
		addShopOrder(fee, username, phone, address, terminalCode, userType, revFeeIdsArr, out_trade_no, PayWays.WEIXIN.getValue(), cUname);
		/*// 订单主表插入
		ShopOrder shopOrder = new ShopOrder();
		shopOrder.setAddress(address);
		shopOrder.setFee(fee);
		shopOrder.setOutTradeNo(out_trade_no);
		shopOrder.setPaymentMethod(PayWays.WEIXIN.getValue());
		shopOrder.setUsername(username);
		shopOrder.setPhone(phone);
		shopOrder.setUserType(userType);
		shopOrder.setTerminalCode(terminalCode);
		shopOrderMapper.insertSelective(shopOrder);


		// 订单详情插入
        ShopOrder shopOrder1 = new ShopOrder();
        shopOrder1.setOutTradeNo(out_trade_no);
		ShopOrder order = shopOrderMapper.selectByCondition(shopOrder1).get(0);
		List<String> shopOrderItems = new ArrayList<>();
		shopOrderItems = JsonUtil.string2Obejct(revFeeIdsArr, shopOrderItems.getClass());
		shopOrderItems.stream().forEach((item) -> {
			ShopOrderItem shopOrderItem = JsonUtil.string2Obejct(item, ShopOrderItem.class);
			shopOrderItem.setOrderId(order.getId());
			shopOrderItemMapper.insertSelective(shopOrderItem);
		});*/

		result.put("out_trade_no", out_trade_no);
		result.put("notifyUrl", WeixinConfig.weixin_notify_url);
		return result;
	}

	@Override
	public int queryOrderStatus(String out_trade_no) {
		Transaction transaction = transactionMapper.queryByOut_trade_no(out_trade_no);
		if(transaction.getStatus() == PayStatus.SUCCESS.getValue()) {
			return 1;
		} else if("SUCCESS".equals(QueryOrder.queryOrder(out_trade_no).getTrade_state())){
			return 1;
		}
		return 0;
	}

	@Override
	public int queryShopOrderStatus(String out_trade_no) {
		ShopOrder shopOrder = new ShopOrder();
		shopOrder.setOutTradeNo(out_trade_no);
		ShopOrder order = shopOrderMapper.selectByCondition(shopOrder).get(0);
		if (order.getStatus() == PayStatus.SUCCESS.getValue()) {
			return 1;
		} else if("SUCCESS".equals(QueryOrder.queryOrder(out_trade_no).getTrade_state())){
			return 1;
		}
		return 0;
	}

	@Override
	public int subPaied(int userId, double money) {
		Paied paied = new Paied();
		paied.setUser(new User().setId(userId));
		paied.setMoney(money);
		paied.setGetTime(new Date());
		paied.setCategories(ExpensesCategories.ALL.getValue());
		paied.setStatus(1);
		return expensesMapper.addPaied(paied);
	}

	@Override
	public List<Map<String, Object>> queryPaidInfoList(int userId, String code, int bid,
			String startTime, String endTime, int page) {
		List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
		
		List<Terminal> terminals = getTerminals(code, bid);
		if (terminals.size() == 0) {
			throw new RuntimeException();
		}
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("terminal_id", terminals.get(0).getId());
		condition.put("user_id", userId);
		condition.put("status", PayStatus.SUCCESS.getValue());
		condition.put("categories", PayCategories.PAYMENT.getValue());
		condition.put("start", (page - 1) * Integer.parseInt(ConfigConstants.INFOS_LIST_NUM));
		condition.put("startTime", startTime);
		condition.put("endTime", endTime);
		condition.put("num", ConfigConstants.INFOS_LIST_NUM);
		
		List<Transaction>  transactions = transactionMapper.queryByCondition(condition);
		
		for(Transaction transaction : transactions){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("gmt_payment", transaction.getGmt_payment());
			map.put("status", transaction.getStatus());
			map.put("out_trade_no", transaction.getOut_trade_no());
			map.put("fee", transaction.getFee());
			map.put("pay_way", transaction.getPayWay());
			map.put("id", transaction.getId());
			maps.add(map);
		}
		
		return maps;
	}

	@Override
	public List<TransactionDetail> queryPaidInfoDetail(int transactionId) {
		return transactionDetailMapper.queryTransactionDetailByTransactionId(transactionId);
	}

	@Override
	public Object queryPaidInfoListCounts(int userId, String code, int bid,
			String startTime, String endTime) {
		List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
		
		List<Terminal> terminals = getTerminals(code, bid);
		if (terminals.size() == 0) {
			throw new RuntimeException();
		}
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("terminal_id", terminals.get(0).getId());
		condition.put("user_id", userId);
		condition.put("status", PayStatus.SUCCESS.getValue());
		condition.put("categories", PayCategories.PAYMENT.getValue());
		condition.put("startTime", startTime);
		condition.put("endTime", endTime);
		
		int totalTicketsCounts = transactionMapper.queryCountsByCondition(condition);
		int totalPages = (totalTicketsCounts % 15 == 0) ? (totalTicketsCounts / 15) : (totalTicketsCounts / 15 + 1);
		return totalPages;
	}

	@Override
	@Transactional
	public Map<String, String> getUnionpayInfo(int fee, String revFeeIdsArr, String code,
			int userId, int bid, String body) throws Exception {
		
		Map<String, String> result = new HashMap<String, String>();
		result = Form05_6_2_AppConsume.getTn(fee + "");
//		String out_trade_no = RandomUtils.nextInt(new Random(), 10000) + "" + System.currentTimeMillis();
		List<Terminal> terminals = getTerminals(code, bid);
		Transaction transaction = new Transaction();
		transaction.setOut_trade_no(result.get("orderId"));
		transaction.setFee(fee);
		transaction.setTerminal(new Terminal().setId(terminals.get(0).getId()));
		transaction.setUser(new User().setId(userId));
		transactionMapper.addTransaction(transaction);
		
		Transaction tra = transactionMapper.queryByOut_trade_no(result.get("orderId"));
		List<String> revFeeIds = JsonUtil.string2Obejct(revFeeIdsArr,
				List.class);
		for (String revFees : revFeeIds) {
			Map<String, String> revFee = JsonUtil.string2Obejct(revFees,
					Map.class);
			TransactionDetail transactionDetail = new TransactionDetail();
			transactionDetail
					.setRevFeeId(String.valueOf(revFee.get("revFeeId")));
			transactionDetail.setFee(Integer.valueOf(revFee.get("revFee")
					.toString()));
            if(StringUtils.isNotEmptyByTrim(revFee.get("CusID"))) {
                transactionDetail.setCusID(String.valueOf(revFee.get("CusID")).trim());
            } else {
                throw new Exception();
            }
			transactionDetail.setIpItemName(String.valueOf(revFee.get("IpItemName")));
			transactionDetail.setTransaction(tra);
			transactionDetailMapper.addTransactionDetail(transactionDetail);
		}
		
		return result;
	}

	@Override
	public Map<String, String> getShopUnionpayInfo(int fee, String username, String phone, String address, int userType, String revFeeIdsArr, String code, String body, String cUname) {
		Map<String, String> result = new HashMap<String, String>();
		result = Form05_6_2_AppConsume.getTn(fee + "");

		/*//  订单主表插入
		ShopOrder shopOrder = new ShopOrder();
		shopOrder.setAddress(address);
		shopOrder.setFee(fee);
		shopOrder.setOutTradeNo(result.get("orderId"));
		shopOrder.setPaymentMethod(PayWays.YINLIAN.getValue());
		shopOrder.setUsername(username);
		shopOrder.setPhone(phone);
		shopOrder.setUserType(userType);
		shopOrder.setTerminalCode(code);
		shopOrderMapper.insertSelective(shopOrder);

		//  订单详情插入
        ShopOrder shopOrder1 = new ShopOrder();
        shopOrder1.setOutTradeNo(result.get("orderId"));
        ShopOrder order = shopOrderMapper.selectByCondition(shopOrder1).get(0);
		List<String> shopOrderItems = new ArrayList<>();
		shopOrderItems = JsonUtil.string2Obejct(revFeeIdsArr, shopOrderItems.getClass());
		shopOrderItems.stream().forEach((item) -> {
			ShopOrderItem shopOrderItem = JsonUtil.string2Obejct(item, ShopOrderItem.class);
			shopOrderItem.setOrderId(order.getId());
			shopOrderItemMapper.insertSelective(shopOrderItem);
		});*/
		addShopOrder(fee, username, phone, address, code, userType, revFeeIdsArr, result.get("orderId"), PayWays.YINLIAN.getValue(), cUname);
		return result;
	}

	@Override
	public Object unionpayVerifyAppData(String unJson) {
		return VerifyAppData.verify(unJson) ? 1 : 0;
	}

	@Override
	public Object shopUnionpayVerifyAppData(String unJson) {
		return VerifyAppData.verify(unJson) ? 1 : 0;
	}

	@Override
	public Object queryUnionpayOrderStatus(String out_trade_no, String txnTime) {
		Transaction transaction = transactionMapper.queryByOut_trade_no(out_trade_no);
		if(transaction.getStatus() == PayStatus.SUCCESS.getValue()) {
			return 1;
		} else if(Form05_6_3_Query.queryStatus(out_trade_no, txnTime) == 1){
			return 1;
		}
		return 0;
	}

	@Override
	public Object queryShopUnionpayOrderStatus(String out_trade_no, String txnTime) {
		ShopOrder shopOrder = new ShopOrder();
		shopOrder.setOutTradeNo(out_trade_no);
		ShopOrder order = shopOrderMapper.selectByCondition(shopOrder).get(0);
		if (order.getStatus() == PayStatus.SUCCESS.getValue()) {
			return 1;
		} else if(Form05_6_3_Query.queryStatus(out_trade_no, txnTime) == 1){
			return 1;
		}
		return 0;
	}

	@Transactional
	@Override
	public int addShopUserInfo(String username, String phone, String address, String code, int userType) {
		ShopUser shopUser = new ShopUser();
		shopUser.setTerminalCode(code);
		List<ShopUser> shopUsers = shopUserMapper.selectByCondition(shopUser);
		if (shopUsers.size() == 1) {
			ShopUserReceivingInfo receivingInfo = new ShopUserReceivingInfo();
			receivingInfo.setAddress(address);
			receivingInfo.setPhone(phone);
			receivingInfo.setUsername(username);
			receivingInfo.setShopUserId(shopUsers.get(0).getId());
			int result = shopUserReceivingInfoMapper.insertSelective(receivingInfo);
			if (result == 0) {
				return 0;
			}
		} else {
			shopUser.setUserType(userType);
			int result = shopUserMapper.insertSelective(shopUser);
			if (result == 0) {
				return 0;
			}
			ShopUserReceivingInfo receivingInfo = new ShopUserReceivingInfo();
			receivingInfo.setAddress(address);
			receivingInfo.setPhone(phone);
			receivingInfo.setUsername(username);
			receivingInfo.setShopUserId(shopUserMapper.selectByCondition(shopUser).get(0).getId());
			int re = shopUserReceivingInfoMapper.insertSelective(receivingInfo);
			if (re == 0) {
				throw new RuntimeException();
			}
		}
		return 1;
	}

	@Override
	public Object queryShopUserReceivingInfo(String code) {
		List<ShopUserReceivingInfo> shopUserReceivingInfos = new ArrayList<>();
		ShopUser record = new ShopUser();
		record.setTerminalCode(code);
		List<ShopUser> shopUsers = shopUserMapper.selectByCondition(record);
		if (shopUsers.size() == 1) {
			ShopUserReceivingInfo shopUserReceivingInfo = new ShopUserReceivingInfo();
			shopUserReceivingInfo.setShopUserId(shopUsers.get(0).getId());
			shopUserReceivingInfos = shopUserReceivingInfoMapper.selectByCondition(shopUserReceivingInfo);
		}
		return shopUserReceivingInfos;
	}

	@Override
	public int updateShopUserReceivingInfo(String username, String phone, String address, Long receivingInfoId) {
		ShopUserReceivingInfo shopUserReceivingInfo = new ShopUserReceivingInfo();
		shopUserReceivingInfo.setAddress(address);
		shopUserReceivingInfo.setPhone(phone);
		shopUserReceivingInfo.setUsername(username);
		shopUserReceivingInfo.setId(receivingInfoId);
		return shopUserReceivingInfoMapper.updateByPrimaryKeySelective(shopUserReceivingInfo);
	}

	@Override
	public int deleteShopUserReceivingInfo(Long receivingInfoId) {
		return shopUserReceivingInfoMapper.deleteByPrimaryKey(receivingInfoId);
	}

	@Override
	public int queryShopScore(String code) {
		ShopUser shopUser = new ShopUser();
		shopUser.setTerminalCode(code);
		return shopUserMapper.selectByCondition(shopUser).get(0).getScore();
	}

	@Override
	public Object queryShopOrderByTerminalCode(String code) {
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setTerminalCode(code);
		List<ShopOrder> shopOrders = shopOrderMapper.selectByCondition(shopOrder);
		shopOrders.sort((ShopOrder shopOrder1, ShopOrder shopOrder2) -> {
			return shopOrder2.getCreateTime().compareTo(shopOrder1.getCreateTime());
		});
		return shopOrders;
	}

    @Override
    public int updateShopOrderStatus(String out_trade_no, int status) {
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setOutTradeNo(out_trade_no.trim());
        shopOrder.setStatus(status);
        return shopOrderMapper.updateByOutTradeNo(shopOrder);
    }

    @Override
    public Object queryShopOrderByStatus() {
        List<Map<String, Object>> results = new ArrayList<>();
        List<Map<String, Object>> result1 = new ArrayList<>();
        List<Map<String, Object>> result2 = new ArrayList<>();
        List<Map<String, Object>> result3 = new ArrayList<>();
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setStatus(1);
        List<ShopOrder> shopOrders = shopOrderMapper.selectByCondition(shopOrder);
        shopOrder.setStatus(2);
        List<ShopOrder> shopOrders1 = shopOrderMapper.selectByCondition(shopOrder);
        shopOrder.setStatus(3);
        List<ShopOrder> shopOrders2 = shopOrderMapper.selectByCondition(shopOrder);
        shopOrders.addAll(shopOrders1);
        shopOrders.addAll(shopOrders2);

        shopOrders.forEach((item) -> {
            Map<String, Object> result = new LinkedHashMap<String, Object>();

            String status = "";
            switch (item.getStatus()){
                case 1:
                    status = "已付款";
                    break;
                case 2:
                    status = "已发货";
                    break;
                case 3:
                    status = "已收货";
                    break;
                default:
                    break;
            }


            ShopOrderItem shopOrderItem = new ShopOrderItem();
            shopOrderItem.setOrderId(item.getId());
            List<ShopOrderItem> shopOrderItems = shopOrderItemMapper.selectByCondition(shopOrderItem);
            StringBuilder itemNames = new StringBuilder();
            StringBuilder itemNums = new StringBuilder();
            StringBuilder itemUnitPrices = new StringBuilder();
            shopOrderItems.forEach((it) -> {
                itemNames.append(it.getName() + "<br>");
                itemNums.append(it.getNum() + "<br>");
                itemUnitPrices.append(((it.getPrice().doubleValue())/100) + "<br>");
            });

            if (item.getStatus() == 1) {
                result.put("outTradeNo", item.getOutTradeNo());
                result.put("createTime", item.getCreateTime());
                result.put("username", item.getUsername());
                result.put("phone", item.getPhone());
                result.put("address", item.getAddress());
                result.put("fee", ((double)item.getFee())/100);
                result.put("status", status);
                result.put("orderStatus", item.getStatus());
                result.put("itemNames", itemNames.toString().trim());
                result.put("itemNums", itemNums.toString().trim());
                result.put("itemUnitPrices", itemUnitPrices.toString().trim());
                result1.add(result);
            }

            if (item.getStatus() == 2) {
                result.put("outTradeNo", item.getOutTradeNo());
                result.put("createTime", item.getCreateTime());
                result.put("username", item.getUsername());
                result.put("phone", item.getPhone());
                result.put("address", item.getAddress());
                result.put("fee", ((double)item.getFee())/100);
                result.put("status", status);
                result.put("orderStatus", item.getStatus());
                result.put("itemNames", itemNames.toString().trim());
                result.put("itemNums", itemNums.toString().trim());
                result.put("itemUnitPrices", itemUnitPrices.toString().trim());
                result2.add(result);
            }

            if (item.getStatus() == 3) {
                result.put("outTradeNo", item.getOutTradeNo());
                result.put("createTime", item.getCreateTime());
                result.put("username", item.getUsername());
                result.put("phone", item.getPhone());
                result.put("address", item.getAddress());
                result.put("fee", ((double)item.getFee())/100);
                result.put("status", status);
                result.put("orderStatus", item.getStatus());
                result.put("itemNames", itemNames.toString().trim());
                result.put("itemNums", itemNums.toString().trim());
                result.put("itemUnitPrices", itemUnitPrices.toString().trim());
                result3.add(result);
            }

        });
        /*results.sort((Map<String, Object> m1, Map<String, Object> m2) -> {
            return Integer.compare((int)m1.get("orderStatus"), (int)m2.get("orderStatus"));
        });*/
        result1.sort((Map<String, Object> m1, Map<String, Object> m2) -> {
            return ((Date)m2.get("createTime")).compareTo((Date)m1.get("createTime"));
        });
        result2.sort((Map<String, Object> m1, Map<String, Object> m2) -> {
            return ((Date)m2.get("createTime")).compareTo((Date)m1.get("createTime"));
        });
        result3.sort((Map<String, Object> m1, Map<String, Object> m2) -> {
            return ((Date)m2.get("createTime")).compareTo((Date)m1.get("createTime"));
        });
        results.addAll(result1);
        results.addAll(result2);
        results.addAll(result3);
        return results;
    }

/*    public static void main(String[] args){
        System.out.println(((double) 10) / 40);
    }*/

}
